<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-05-08 10:10:08
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-05-08 15:21:17
 * @FilePath: /free-learning/src/views/dashboard/components/course-likes.vue
 * @Description: 课程获赞数量统计图
-->
<template>
  <div ref="chartRef" :style="{ width, height }" />
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { EChartsOption } from "echarts";
import { useECharts } from "@/hooks/useECharts";

defineOptions({
  name: "CourseLikes",
});

const props = defineProps<{
  width?: string;
  height?: string;
  data?: {
    courses: string[];
    likes: string[];
  };
}>();

const chartRef = ref<HTMLElement>();
let chart: ReturnType<typeof useECharts>;

// 图表配置
const getOptions = (data: any): EChartsOption => {
  return {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.courses || [],
      axisLabel: {
        interval: 0,
        rotate: 30,
        overflow: "truncate",
        width: 120,
      },
      axisLine: {
        lineStyle: {},
      },
    },
    yAxis: {
      type: "value",
      name: "获赞数",
      axisLine: {
        show: true,
        lineStyle: {
          color: "#ddd",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#eee",
        },
      },
    },
    series: [
      {
        name: "获赞数",
        type: "bar",
        barWidth: "60%",
        data: data.likes || [],
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#67C23A",
              },
              {
                offset: 1,
                color: "#95D475",
              },
            ],
          },
          borderRadius: [4, 4, 0, 0],
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
        },
      },
    ],
  };
};

// 加载图表数据
const loadChartData = async () => {
  try {
    console.log(props.data);

    if (chart) {
      chart.setOption(getOptions(props.data));
    }
  } catch (error) {
    console.error("加载课程获赞数据失败", error);
  }
};
watch(
  () => props.data,
  () => {
    if (chart) {
      chart.setOption(getOptions(props.data));
    }
  }
);
onMounted(() => {
  if (chartRef.value) {
    chart = useECharts(chartRef.value);
    loadChartData();
  }
});
</script>
